﻿/*
 * 2008 (c) ralfoide at gmail com
 * Project: SharpFlow
 * License: GPL
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Alfray.SharpFlow.Core;
using Alfray.SharpFlow.Utils;

namespace Alfray.SharpFlow.UI {
    /// <summary>
    /// Class that defines the main form.
    /// It has a menu bar and so other stuff.
    /// </summary>
    public partial class MainForm : AutoSavingForm {
        // The main reference on the "data core" singleton. Useful to make sure
        // it keeps allocated for the life time of the application.
        private DataCore mCore;
        // True if we should perform delayed initialization the first time the
        // form is activated
        private bool mFirstTimeActivated = true;
        // Singleton wrapper for the debug log form
        private SingletonForm<DebugLogForm> mDebugFormWrapper = new SingletonForm<DebugLogForm>();
        // Singleton wrapper for the preference form
        private SingletonForm<PreferencesForm> mPrefsFormWrapper = new SingletonForm<PreferencesForm>();

        /// <summary>
        /// Constructor.
        /// </summary>
        public MainForm() {
            // Create the data core and keep a reference around.
            // Users should get DataCore.singleton to get its instance.
            mCore = DataCore.singleton;
            InitializeComponent();

            mCore.preferences.load();
            loadWindowPosition();
            mCore.logger.append("Started");
        }

        /// <summary>
        /// Closes the application when File > Exist is selected
        /// </summary>
        private void mExitToolStripMenuItem_Click(object sender, EventArgs e) {
            this.Close();
        }

        /// <summary>
        /// Toggles the debug log window (or creates it the first time)
        /// </summary>
        private void mDebugLogToolStripMenuItem_Click(object sender, EventArgs e) {
            mDebugFormWrapper.toggleVisibility();
            mCore.logger.append("Toggle debug log");
        }

        /// <summary>
        /// Toggles the preference window (or creates it the first time)
        /// </summary>
        private void preferencesToolStripMenuItem_Click(object sender, EventArgs e) {
            mPrefsFormWrapper.toggleVisibility();
        }

        /// <summary>
        /// Called before the window is closed.
        /// Closes the debug log too.
        /// </summary>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
            mDebugFormWrapper.close();
            mPrefsFormWrapper.close();
            saveWindowPosition();
            mCore.preferences.save();
        }

        /// <summary>
        /// Called when the form is activated.
        /// The first time the app is activated, we perform some delayed initializations
        /// </summary>
        private void MainForm_Activated(object sender, EventArgs e) {
            if (mFirstTimeActivated) {
                mFirstTimeActivated = false;

                Thread thread = new Thread(delegate() {
                    setStatus("Updating OFX Server List...", 0);
                    mCore.initializeFIList();
                    setStatus("Ready", 0);
                });
                thread.Start();
            }
        }

        /// <summary>
        /// Updates the status text and progress bar of the status strip.
        /// This method is safe to call from worker threads.
        /// </summary>
        /// <param name="message">Status Text, only updated if not null.</param>
        /// <param name="progress">Progress value, only updated if >= 0</param>
        private void setStatus(string message, int progress) {
            if (!mStatusTrip.InvokeRequired) {
                if (message != null) mStatusStripLabel.Text = message;
                if (progress >= 0) mStatusStripProgressBar.Value = progress;
            } else {
                // Invoke itself on the UI thread
                InvokeDelegate d = delegate() {
                    this.setStatus(message, progress);
                };
                mStatusTrip.Invoke(d);
            }
        }

        private void mViewToolStripMenuItem_DropDownOpening(object sender, EventArgs e) {
            mDebugLogToolStripMenuItem.Checked = mDebugFormWrapper.isVisible;
            mPreferencesToolStripMenuItem.Checked = mPrefsFormWrapper.isVisible;
        }

        private void mLoadStatementsToolStripMenuItem_Click(object sender, EventArgs e) {
            if (mCore.getCurrentFI() == null) {
                mPrefsFormWrapper.open();
            } else {
                mCore.loadStatements(mCore.getCurrentFI());
            }
        }
    }
}
